package de.itagile.hypersphere

import de.itagile.hypersphere.EntityTemplateclass EjbTemplate extends Template{
	def ejbJar
	def adapter
	def entityFactory
	
	public EjbTemplate(ejbJar, metaDataAdapter, entityFactory) {
		this.ejbJar = ejbJar
		this.adapter = metaDataAdapter
		this.entityFactory = entityFactory
	}
	
	def getEntities() {
		return ejbJar.enterprisebeans.entity
	}
	
	def findRelationsByName(def name) {
		def result = new HashSet();
		if (ejbJar?.relationships == null)
			return result
		ejbJar.relationships.ejbrelation.ejbrelationshiprole.relationshiprolesource.ejbname.
			findAll{it.text() == name}.'..'.'..'.'..'.each{result.add(createRelation(it))}
		return result.asList()
	}
	
	private createRelation(def relation) {
		return new Relation(relation)
	}
	
	def getFields(def fields) {
		def list = new ArrayList()
		fields.each {
			def id = it.'@id'
			list.add([name:it.fieldname.text(), id:id, type:adapter.getType(id), column:adapter.getColumn(id)])
		}
		return list
	}
	
	def getTable(def entity) {
		return adapter.getTable(entity.@'id')
	}
	
	public getEntityTemplate(entity) {
		return entityFactory.create(
				entity.ejbname.text(),
				extractPackage(entity.local.text()),
				getTable(entity),
				getFields(entity.cmpfield),
				searchRelationships(entity))
	}
	
	public searchRelationships(def entity) {
		def name = entity.ejbname.text()
		def relations = findRelationsByName(name)
		List result = new ArrayList()
		relations?.each{
			def oppositeEntityName = it.getOppositeEntityName(name)
			result.add([
		            	fqn:getEntityFqn(oppositeEntityName), 
			            type:it.getType(oppositeEntityName),
			            collection:it.getCollection(name)
			            ])
        }
		return result
	}
	
	def getEntityFqn(def name) {
		def local = ejbJar.enterprisebeans.entity.ejbname.find{it.text() == name}.'..'.local.text()
		return extractPackage(local) + "." + name
	}
	
	public start() {
		def entities = ejbJar.enterprisebeans.entity
		entities.each({
			getEntityTemplate(it).start();
		})
	}
}